/**
 * crawler
 *
 * outlook@China software studio
 * Copyright (c) 2008-2010. All Rights Reserved.
 * http://www.outlook.com
 */

package org.outlook.crawler.task;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.outlook.common.log.LogUtil;
import org.outlook.common.queue.Task;
import org.outlook.crawler.client.domain.Source;
import org.outlook.crawler.client.pojo.Webinfo;
import org.outlook.crawler.util.CrawlTaskMonitor;
import org.outlook.crawler.util.Fetcher;
import org.outlook.crawler.util.parser.WebinfoProcessor;

/**
 * function:
 * @author Watson email: watson.wu@hotmail.com
 * @date 2011
 */
public class ImpostorTask extends Task {
	
	private Log logger = LogFactory.getLog(ImpostorTask.class);
	
	private Source source;

	public ImpostorTask(String str) {
		super(str);
	}

	@Override
	public void run() {
		super.run();
		final String url = (String)getMsg();
		LogUtil.debug(logger, "start crawl ", url);
		
		//TODO
		if(source == null)
			source = new Source();
		
		//TODO judge by the success precent, if low try to use proxy or other fetcher;
		
		Fetcher fetcher = new Fetcher();
		Webinfo webinfo = fetcher.fetch(url, source);
		
		try {
			WebinfoProcessor webinfoProcessor = new WebinfoProcessor();
			webinfoProcessor.parseAndSave(webinfo, source);
			CrawlTaskMonitor.updatePage(url, webinfo.getStatus());
			LogUtil.debug(logger, "finish crawl ", url);
		} catch (Exception e) {
			LogUtil.error(logger, e.getMessage());
			LogUtil.debug(logger, "crawl ", url, "occur exception");
		}
	}

	public Source getSource() {
		return source;
	}

	public void setSource(Source source) {
		this.source = source;
	}

	@Override
	public boolean equals(Object obj) {
		if(super.equals(obj)) return true;
		if(obj instanceof ImpostorTask) {
			ImpostorTask task = (ImpostorTask) obj;
			EqualsBuilder equalsBuilder = new EqualsBuilder().append(getMsg(), task.getMsg());
			if(source != null)
				equalsBuilder.append(source, task.getSource());
			return equalsBuilder.isEquals();
		}
		return false;
	}

	@Override
	public String toString() {
		return new StringBuilder().append(getMsg()).append(source.toString()).toString();
	}

}
